<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="48px">
      <el-form-item label="编号" prop="reportNumber">
        <el-input
            v-model="queryParams.reportNumber"
            placeholder="请输入编号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="reportName">
        <el-select
            v-model="queryParams.reportName"
            placeholder="请选择名称"
            clearable
        >
          <el-option
              v-for="dict in dict.type.report_class"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptAbbreviation">
        <el-select v-model="queryParams.deptAbbreviation" placeholder="请选择部门" clearable @keyup.enter.native="handleQuery">
          <el-option
              v-for="dict in dict.type.dept_abbreviation"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="reportDate">
        <el-date-picker
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="dateRangeReportDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['quality:physicalReport:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['quality:physicalReport:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['quality:physicalReport:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip
            class="box-item"
            effect="dark"
            content="导出所选通报考核汇总表"
            placement="top"
        >
          <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExportFine"
              v-hasPermi="['quality:physicalReport:export']"
          >考核</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip
            class="box-item"
            effect="dark"
            content="导出进机数据列表用于闭环"
            placement="top"
        >
          <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExportCycle"
              v-hasPermi="['quality:physicalReport:export']"
          >闭环</el-button>
        </el-tooltip>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="physicalReportList"
        @selection-change="handleSelectionChange"
        @row-click="handlePreview"
        :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="通报id" align="center" prop="reportId" v-if="true" width="96" sortable/>
      <el-table-column label="编号" align="center" prop="reportNumber"/>
      <el-table-column label="名称" align="center" prop="reportName" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.report_class" :value="scope.row.reportName"/>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptAbbreviation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dept_abbreviation" :value="scope.row.deptAbbreviation"/>
        </template>
      </el-table-column>
      <el-table-column label="日期" align="center" prop="reportDate" width="180" sortable>
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click.stop="handlePreview(scope.row)"
              v-hasPermi="['quality:physicalReport:edit']"
          >预览</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click.stop="handleUpdate(scope.row)"
              v-hasPermi="['quality:physicalReport:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click.stop="handleDelete(scope.row)"
              v-hasPermi="['quality:physicalReport:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改质量通报对话框 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="75%"
        v-if="configDialogVisible"
        destroy-on-close
        append-to-body
        :before-close="handleDialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="编号" prop="reportNumber">
              <el-input v-model="form.reportNumber" placeholder="请输入编号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="名称" prop="reportName">
              <el-select v-model="form.reportName" placeholder="请输入名称" clearable>
                <el-option
                    v-for="dict in dict.type.report_class"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="日期" prop="reportDate">
              <el-date-picker clearable
                              v-model="form.reportDate"
                              type="date"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="罚金" prop="defectFine">
              <el-input v-model="form.defectFine" placeholder="请输入罚金"  @input="handleChangeDataForm($event)" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="width: 96%">
          <el-col>
            <el-form-item label="措施" prop="reportMeasure">
              <el-input
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 50 }"
                  v-model="form.reportMeasure"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">质量问题信息</el-divider>
        <el-table
            :data="qualityPhysicalDefectList"
            :row-class-name="rowDefectIndex"
            @selection-change="handleDefectSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="80"/>
          <el-table-column label="件号" prop="partNumber" >
            <template slot-scope="scope">
              <el-input
                  v-model="scope.row.partNumber"
                  placeholder="请输入件号"
                  @change="((val)=>{autoFillPartName(val, scope.row)})"
              />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="partName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.partName" placeholder="请输入名称" />
            </template>
          </el-table-column>
          <el-table-column label="分类" prop="defectClassification">
            <template slot-scope="scope">
              <el-cascader
                  v-model="scope.row.defectClassification"
                  placeholder="问题分类"
                  :options="defectClassList"
                  filterable
                  :show-all-levels="false"
                  clearable
                  popper-class="self-el-cascader"
                  :props = "{emitPath:false}"
              />
            </template>
          </el-table-column>
          <el-table-column label="责任人" prop="workersName">
            <template slot-scope="scope">
              <el-cascader
                  v-model="scope.row.workersName"
                  placeholder="责任人"
                  :options="clerkList"
                  filterable
                  :show-all-levels="false"
                  clearable
                  popper-class="self-el-cascader"
                  :props = "{emitPath:false}"
                  @change="changedMatRemark(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="罚款" prop="defectFine" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.defectFine" placeholder="正整数" />
            </template>
          </el-table-column>
          <!--          用v-model绑定-->
          <el-table-column label="图片" align="center" prop="defectPicture" width="210">
            <template slot-scope="scope">
              <image-upload
                  v-model="scope.row.defectPicture"
                  :is-show-tip="false"
                  :limit="1"
                  :fileSize="1"
              />
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDefect">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleCopyDefect">复制</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDefect">删除</el-button>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <div>
      <report-preview
          :visible.sync="preview"
          :form = form
      />
    </div>
  </div>
</template>

<script>
import {
  addPhysicalReport,
  delPhysicalReport,
  getMaxNumber,
  getPhysicalReport,
  listPhysicalReport,
  updatePhysicalReport
} from '@/api/quality/physicalReport'
import { positiveIntNum1, required } from '@/utils/rules'
import { getInfo } from '@/api/login'
import ReportPreview from '../common/ReportPreview.vue'
import { listClerk } from '@/api/system/user'
import { queryClass } from '@/api/quality/class'

export default {
  name: "PhysicalReport",
  components: {ReportPreview},
  dicts: ['dept_abbreviation', 'typical_workpiece', 'dept_fullname', 'report_class'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedQualityPhysicalDefect: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 质量通报表格数据
      physicalReportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      configDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reportNumber: undefined,
        reportName: undefined,
        reportAbstract: undefined,
        deptAbbreviation: undefined,
        reportDate: undefined,
        reportMeasure: undefined
      },
      // 表单参数
      form: {},
      // 质量问题表格数据
      qualityPhysicalDefectList: [],
      // 日期范围
      dateRangeReportDate: [],
      //用户信息
      user:null,
      //职工列表
      clerkList: null,
      //问题分类列表
      defectClassList: null,
      //通报预览开关
      preview:false,
      // 表单校验
      rules: {
        reportNumber: [required],
        reportName: [required],
        reportDate: [required],
        reportMeasure: [required],
        defectFine: [required],
      }
    };
  },
  created() {
    this.getList();
    this.getUser();
    this.getClassList();
  },
  methods: {
    /** 查询质量通报列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.dateRangeReportDate && '' !== this.dateRangeReportDate) {
        this.queryParams.params["beginReportDate"] = this.dateRangeReportDate[0];
        this.queryParams.params["endReportDate"] = this.dateRangeReportDate[1];
      }
      listPhysicalReport(this.queryParams).then(response => {
        this.physicalReportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取当前用户信息 */
    getUser(){
      getInfo().then(res=>{
        //获取用户信息
        this.user = res.data.user;
        const deptId = Number(this.user.deptId);
        this.getClerkList(deptId);
      });
    },

    /** 获取当前职工信息 */
    getClerkList(deptId){
      const queryParams = {};
      // queryParams.deptId = deptId;
      listClerk(queryParams).then(response => {
        this.clerkList = Object.freeze(response);
      });
    },

    /** 查询问题分类列表 */
    getClassList() {
      const queryParams = {};
      queryClass(queryParams).then(response => {
        this.defectClassList = Object.freeze(response);
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.configDialogVisible = false;
      this.queryParams.deptAbbreviation = null;
      this.reset();
    },

    handleChangeDataForm (e) {
      this.$forceUpdate()
    },

    // 表单重置
    reset() {
      this.form = {
        reportId: undefined,
        reportNumber: undefined,
        reportName: undefined,
        reportAbstract: undefined,
        deptAbbreviation: undefined,
        reportDate: undefined,
        reportMeasure:undefined,
        defectList: undefined
      };
      this.qualityPhysicalDefectList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeReportDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.configDialogVisible = true;
      this.title = "添加质量通报";
      const deptId = this.user.deptId;
      this.form.deptAbbreviation = deptId;
      this.form.reportMeasure =  "要求各工组立即举一反三，进行排查、整改，操作者严格文明操作，" +
          "坚持“不制造、不传递、不接收、不使用”不合格品，强化内部上下序关系，避免将问题带到下序。";
      this.queryParams.deptAbbreviation = deptId;
      getMaxNumber(this.queryParams).then(res=>{
        this.form.reportNumber = res+1;
      })
      this.form.defectFine = 50;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const reportId = row.reportId || this.ids
      getPhysicalReport(reportId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.qualityPhysicalDefectList = this.form.defectList;
        this.open = true;
        this.configDialogVisible = true;
        this.title = "修改质量通报";
        this.form.defectFine = 50;
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.defectList = this.qualityPhysicalDefectList;
          if (this.form.reportId != null) {
            updatePhysicalReport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.configDialogVisible = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addPhysicalReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.configDialogVisible = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const reportIds = row.reportId || this.ids;
      this.$modal.confirm('是否确认删除质量通报编号为"' + reportIds + '"的数据项？').then(() => {
        this.loading = true;
        return delPhysicalReport(reportIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 导出考核按钮操作 */
    handleExport() {
      this.download('quality/physicalReport/export', {
        ...this.queryParams
      }, `physicalReport_${new Date().getTime()}.xlsx`)
    },

    /** 导出考核按钮操作 */
    handleExportFine(row) {
      const reportIds = row.reportId || this.ids;
      if (reportIds.length!==0){
        this.download('quality/physicalReport/exportFine/'+reportIds, {
          ...this.queryParams
        }, `考核汇总表_${new Date().getTime()}.xlsx`)
      }else {
        this.$modal.msgError("未选择导出项");
      }
    },

    /** 导出闭环按钮操作 */
    handleExportCycle(row) {
      const reportIds = row.reportId || this.ids;
      if (reportIds.length!==0){
        this.download('quality/physicalReport/exportCycle/'+reportIds, {
          ...this.queryParams
        }, `闭环汇总表_${new Date().getTime()}.xlsx`)
      }else {
        this.$modal.msgError("未选择导出项");
      }
    },

    /** 质量问题序号 */
    rowDefectIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 质量问题添加按钮操作 */
    handleAddDefect() {
      let obj = {};
      obj.partNumber = "";
      obj.partName = "";
      obj.defectClassification = "";
      obj.workersId = "";
      obj.workersName = "";
      obj.defectPicture = "";
      obj.defectFine = this.form.defectFine;
      obj.deptAbbreviation = this.form.deptAbbreviation;
      obj.defectDate = "";
      this.qualityPhysicalDefectList.push(obj);
    },

    /** 质量问题删除按钮操作 */
    handleDeleteDefect() {
      if (this.checkedQualityPhysicalDefect.length === 0) {
        this.$modal.msgError("请先选择要删除的质量问题数据");
      } else {
        const qualityPhysicalDefectList = this.qualityPhysicalDefectList;
        const checkedQualityPhysicalDefect = this.checkedQualityPhysicalDefect;
        this.qualityPhysicalDefectList = qualityPhysicalDefectList.filter(function(item) {
          return checkedQualityPhysicalDefect.indexOf(item.index) === -1
        });
      }
    },

    /** 复选框选中数据 */
    handleDefectSelectionChange(selection) {
      this.checkedQualityPhysicalDefect = selection.map(item => item.index)
    },

    /** 点击列表预览通报内容*/
    handlePreview(row){
      this.reset();
      const reportId = row.reportId || this.ids;
      getPhysicalReport(reportId).then(response => {
        this.form = response.data;
        this.form.defectList = response.data.defectList;
        const deptAbbreviation = this.form.deptAbbreviation;
        const reportName = this.form.reportName;
        this.form.deptAbb = this.selectDictLabel(this.dict.type.dept_abbreviation, deptAbbreviation);
        this.form.deptName = this.selectDictLabel(this.dict.type.dept_fullname, deptAbbreviation);
        this.form.reportName = this.selectDictLabel(this.dict.type.report_class, reportName);
        this.preview = true;
      });
    },

    /** 复制上一条问题*/
    handleCopyDefect(){
      let lastDefect = this.qualityPhysicalDefectList.slice(-1);
      if (lastDefect.length!==0){
        const copyObj = lastDefect[0];
        const obj = {};
        obj.partNumber = copyObj.partNumber;
        obj.partName = copyObj.partName;
        obj.defectClassification = copyObj.defectClassification;
        obj.wokersId = copyObj.wokersId;
        obj.wokersName = copyObj.wokersName;
        obj.defectPicture = "";
        obj.defectFine = copyObj.defectFine;
        obj.deptAbbreviation = copyObj.deptAbbreviation;
        obj.defectDate = copyObj.defectDate;
        this.qualityPhysicalDefectList.push(obj);
      }else {
        this.handleAddDefect();
      }
    },

    /**匹配五大件名称*/
    autoFillPartName(modelValue,row){
      let reg = /([^-]*)$/;
      const partNumber = Number(modelValue.match(reg)[0].replace(/[^0-9]+/,""));
      const label = this.selectDictLabel(this.dict.type.typical_workpiece, partNumber);
      console.log(label);
      row.partName = isNaN(label) ? label : "";
    },

    /**自动匹配工号*/
    changedMatRemark(row) {
      //利用正则匹配小括号内工号
      const id = row.workersName.match(/\(([^)]*)\)/);
      //转为数字
      row.workersId = id[1];
    },

    //关闭预览窗口
    closePreviewDialog(){
      this.dialogVisible = false;
      this.reset();
    },

    handleDialogClose(){
      this.configDialogVisible = false;
      this.reset();
    }
  }
};
</script>
<style scoped>

::v-deep .el-textarea__inner {
  font-family: Arial, Helvetica, sans-serif !important;
}

</style>
<style lang="scss">

.self-el-cascader {
  .el-cascader-node.in-active-path,
  .el-cascader-node.is-active,
  .el-cascader-node.is-selectable.in-checked-path {
    color: #4e5ef1;
  }
  .el-cascader-panel {
    height: 360px;
  }
  .el-cascader-menu__wrap {
    // 设置选择器省市区分块面板高度
    height: 360px;
  }
}
</style>
